import 'dart:math';

import 'package:flutter/material.dart';
import 'package:tv_live/index.dart';
import 'package:video_player/video_player.dart';

import 'config.dart';
import 'log.dart';

class TvVideoplayWidget extends StatefulWidget {
  const TvVideoplayWidget({
    super.key,
    this.index = 0,
    required this.urls,
    this.header,
  });
  final int index;
  final List<String> urls;
  final Map<String, String>? header;
  @override
  State<TvVideoplayWidget> createState() => _TvVideoplayWidgetState();
}

class _TvVideoplayWidgetState extends State<TvVideoplayWidget> {
  VideoPlayerController? _controller;
  final ApiResult _apiResult = ApiResult.init();

  String get videoUrl => widget.urls[_index];
  int _index = 0;
  @override
  void dispose() {
    super.dispose();
    _controller?.dispose();
  }

  @override
  void initState() {
    _index = max(0, widget.index);
    super.initState();
    _initUrl();
  }

  void _initUrl() {
    if (_controller != null) {
      _controller!.dispose();
    }
    if (widget.urls.isEmpty) {
      setState(() {
        _apiResult.fail("地址错误-1");
      });
      return;
    }
    if (!_apiResult.isInit) {
      setState(() {
        _apiResult.init();
      });
    }
    print("开始加载视频：${videoUrl}");
    _controller = _makeController(videoUrl.trim());
    _controller!.initialize().then((_) {
      Log.i("Video initialized successfully");
      setState(() {
        _apiResult.success(videoUrl);
        _controller?.play();
      });
    }, onError: (e, s) {
      Log.e(e, stackTrace: s);
      setState(() {
        _apiResult.fail("线路${widget.index + 1} 加载失败");
      });
    });
  }

  VideoPlayerController _makeController(String url) {
    return VideoPlayerController.networkUrl(
      Uri.parse(url),
      httpHeaders: widget.header ??
          const {
            "User-Agent":
                "com.android.chrome/131.0.6778.200 (Linux;Android 9) AndroidXMedia3/1.6.1",
          },
      formatHint: loadFormatHint(url.toLowerCase()),
    );
  }

  VideoFormat? loadFormatHint(String url) {
    if (url.endsWith(".m3u8") || url.endsWith(".m3u")) {
      return VideoFormat.hls;
    }
    return null;
  }

  @override
  void didUpdateWidget(covariant TvVideoplayWidget oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.index != oldWidget.index ||
        oldWidget.urls.length != widget.urls.length ||
        videoUrl != oldWidget.urls[oldWidget.index]) {
      _index = max(0, widget.index);
      _initUrl();
    }
  }

  @override
  Widget build(BuildContext context) {
    if (widget.urls.isEmpty) {
      return const Text("没有播放地址",
          style: TextStyle(color: Colors.white, fontSize: 18));
    }
    Size size = MediaQuery.sizeOf(context);
    var width = size.width;
    var boxWidth = min(width, size.height) / 5;
    // var height = size.height;
    if (_apiResult.isInit || _apiResult.isLoading || _controller == null) {
      return SizedBox(
        width: boxWidth,
        height: boxWidth,
        child: const CircularProgressIndicator(
          color: Colors.blue,
          strokeWidth: circle_progress_width,
        ),
      );
    }
    if (_apiResult.isError) {
      return Text(_apiResult.message,
          style: const TextStyle(color: Colors.white));
    }
    return videoView(context);
  }

  Widget videoView(BuildContext context) {
    return AspectRatio(
      aspectRatio: _controller!.value.aspectRatio,
      child: VideoPlayer(_controller!),
    );
  }
}
